package com.samsungmobile.common_module;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Vector;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.samsungmobile.common.Logger;
import com.samsungmobile.common.channel.ServletManager;
import com.samsungmobile.common.db.value.StringValue;
import com.samsungmobile.common.email.EmailCheck;
import com.samsungmobile.common.util.EasyString;


/**
 * @author Jinwoo
 *
 */
public class RegisterEmail extends ServletManager {
	
	//Parameter Values
	private String spMst_Cd 			= "";
	private String spCountry_Cd 		= "";
	private String spLang_Cd 			= "";
	private String spEmail 				= "";
	
	private String spFirst_Name 		= "";
	private String spLast_Name 			= "";
	private String spPhone_Num			= "";

	//Return Values
	private final String sfRTN_EMPTY_MST_CD 		= "EMPTY_MST_CD";
	private final String sfRTN_EMPTY_COUNTRY_CD 	= "EMPTY_COUNTRY_CD";
	private final String sfRTN_EMPTY_LANG_CD 		= "EMPTY_LANG_CD";
	private final String sfRTN_EMPTY_EMAIL 			= "EMPTY_EMAIL";
	
	private final String sfRTN_INVALID_MST_CD 		= "INVALID_MST_CD";
	private final String sfRTN_INVALID_COUNTRY_CD 	= "INVALID_COUNTRY_CD";
	private final String sfRTN_INVALID_LANG_CD 		= "INVALID_LANG_CD";
	private final String sfRTN_INVALID_EMAIL 		= "INVALID_EMAIL";
	
	private final String sfRTN_DUPLICATE_EMAIL 		= "DUPLICATE_EMAIL";
	private final String sfRTN_ERROR_SYSTEM 		= "ERROR_SYSTEM";
	private final String sfRTN_SUCCESS 				= "SUCCESS";

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void process() throws Exception {

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		HttpSession session = req.getSession(false);
		
		HashMap hm = new HashMap();
		
		try{
			setParams(req);
			
			checkValidation(res, out);
			
			setMap(hm);
			
			saveOnDB(res, out);
			
			out.println(sfRTN_SUCCESS);
			
			hm.put("RESULT", sfRTN_SUCCESS);
			
		}catch(Exception e){
			
			out.println(e.getMessage());
			hm.put("RESULT", e.getMessage());
			
		}finally{
			writeLog(hm);
		}

	}
	
	private void saveOnDB(HttpServletResponse response, PrintWriter out) throws Exception{
		
		StringBuffer sbQuery = new StringBuffer();
		
		sbQuery.append("insert into G_GATEPAGE_EMAIL\n");			
		sbQuery.append("( mst_cd, country_cd, lang_cd, email, first_name, last_name, hp_num )\n"); 
		sbQuery.append("values( ?, ?, ?, LOWER(?), ?, ?, ?)");
		
		Vector vParam = new Vector();
		vParam.add(new StringValue(spMst_Cd));
        vParam.add(new StringValue(spCountry_Cd));    
        vParam.add(new StringValue(spLang_Cd));    
        vParam.add(new StringValue(spEmail));    
        vParam.add(new StringValue(spFirst_Name));    
        vParam.add(new StringValue(spLast_Name));    
        vParam.add(new StringValue(spPhone_Num));    
        
		updateQuery(sbQuery.toString(), vParam);
	}
	/**
	 * @param hm
	 */
	private void setMap(HashMap hm){
		
    	hm.put("MST_CD"			, spMst_Cd);
    	hm.put("COUNTRY_CD"		, spCountry_Cd);
    	hm.put("LANG_CD"		, spLang_Cd);
    	hm.put("EMAIL"			, spEmail);
    	hm.put("FIRST_NAME"		, spFirst_Name);
    	hm.put("LAST_NAME"		, spLast_Name);
    	hm.put("HP_NUM"			, spPhone_Num);		
	}
	
	/**
	 * @param request
	 */
	private void setParams(HttpServletRequest request){
		
		spMst_Cd 		= EasyString.toString(request.getParameter("mst_cd")).trim();
		spCountry_Cd 	= EasyString.toString(request.getParameter("country_cd")).trim();
		spLang_Cd 		= EasyString.toString(request.getParameter("lang_cd")).trim();
		spEmail 		= EasyString.toString(request.getParameter("email")).trim();
		
		spFirst_Name 	= EasyString.toString(request.getParameter("first_name")).trim();
		spLast_Name 	= EasyString.toString(request.getParameter("last_name")).trim();
		spPhone_Num 	= EasyString.toString(request.getParameter("phone_number")).trim();
		
	}
	
	/**
	 * @param response
	 * @param out
	 * @throws Exception
	 */
	private void checkValidation(HttpServletResponse response, PrintWriter out) throws Exception{
	
		EmailCheck ec = new EmailCheck();
		
		if(spMst_Cd.equals("")){
			throw new Exception(sfRTN_EMPTY_MST_CD);
			
		}else if(spMst_Cd.length() != 5){
			throw new Exception(sfRTN_INVALID_MST_CD);

		}else if(!isExitMstCd()){
			throw new Exception(sfRTN_INVALID_MST_CD);
						
		}else if(spCountry_Cd.equals("")){
			throw new Exception(sfRTN_EMPTY_COUNTRY_CD);
			
		}else if(spCountry_Cd.length() != 2){
			throw new Exception(sfRTN_INVALID_COUNTRY_CD);
			
		}else if(spLang_Cd.equals("")){
			throw new Exception(sfRTN_EMPTY_LANG_CD);
			
		}else if(spLang_Cd.length() != 2){
			throw new Exception(sfRTN_INVALID_LANG_CD);
			
		}else if(spEmail.equals("")){
			throw new Exception(sfRTN_EMPTY_EMAIL);
			
		}else if(!isEmail(spEmail)){
			throw new Exception(sfRTN_INVALID_EMAIL);
			
		}else if(!(ec.CheckEmailServer(spEmail)) ){
			throw new Exception(sfRTN_INVALID_EMAIL);

		}else if(isExistEmail()){
			throw new Exception(sfRTN_DUPLICATE_EMAIL);
			
		}

	}
	
	private boolean isExitMstCd(){
		
		StringBuffer sbQuery = new StringBuffer();
		
		
		sbQuery.append("SELECT count(MST_CD)\n");
		sbQuery.append("FROM G_PMGM_MST\n");
		sbQuery.append("where mst_cd = ?\n");
		sbQuery.append("	  and status_cd = 'O'\n");
		
		Vector vParam = new Vector();
		vParam.add(new StringValue(spMst_Cd));
        
        String sRtn = singleValueQuery(sbQuery.toString(), vParam);
        
        return "1".equals(sRtn);
	}	

	private boolean isExistEmail(){
		
		StringBuffer sbQuery = new StringBuffer();
		
		sbQuery.append("SELECT count(EMAIL)\n");
		sbQuery.append("FROM G_GATEPAGE_EMAIL\n");
		sbQuery.append("WHERE MST_CD = ?\n");
		sbQuery.append("AND COUNTRY_CD = ?\n");
		sbQuery.append("AND LANG_CD = ?\n");
		sbQuery.append("AND EMAIL = LOWER(?)\n");
		
		Vector vParam = new Vector();
		vParam.add(new StringValue(spMst_Cd));
        vParam.add(new StringValue(spCountry_Cd));    
        vParam.add(new StringValue(spLang_Cd));    
        vParam.add(new StringValue(spEmail));    
        
        String sRtn = singleValueQuery(sbQuery.toString(), vParam);
        
        return "1".equals(sRtn);
	}
	

	
	/**
	 * @param hm
	 */
	private void writeLog(HashMap hm){
		
		String sResult = (String)hm.get("RESULT");
		Logger.LOG_REGISTER_EMAIL.info("Register Eamil : "+sResult
						+"\tEmail : "+spEmail);
		
	}
	
	
	/**
	 * @param sEmail
	 * @return
	 */
	private static boolean isEmail(String sEmail) {
        if (sEmail==null) return false;
        boolean bRtn = Pattern.matches("[\\w\\~\\-\\.]+@[\\w\\~\\-]+(\\.[\\w\\~\\-]+)+", sEmail.trim());
        return bRtn;
    }
}
	